package se19team1e.gui.awt;

import java.awt.Choice;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import se19team1e.entity.DepartmentDTO;
import se19team1e.util.StringUtil;

/**
 * 
 * This is a helper choice gui element that manipulates department names to department objects.
 * 
 * @author lai shiaw san
 *
 */
@SuppressWarnings("serial")
public class DepartmentComboBox extends Choice {
    
    /**
     * Map of department name to dto object for lookup.
     */
    private final Map< String, DepartmentDTO > departmentMap = new HashMap< String, DepartmentDTO >();
    
    /**
     * Allow no value to be selected.
     */
    private final boolean allowNull;

    /**
     * Constructs the department combo box.
     * @param allowNull Allow no value to be selected.
     */
    public DepartmentComboBox( boolean allowNull ) {
        this.allowNull = allowNull;
    }

    /**
     * Initialize the combo box with a new set of departments.
     * <p>
     * Previous values are all removed.
     * </p>
     * @param departments Departments to initialize the combo box with.
     */
    public void initialize( List<DepartmentDTO> departments ) {
        // clear previous values
        this.departmentMap.clear();
        this.removeAll();
        
        // build up new map
        for ( DepartmentDTO department : departments ) {
            // build up unique name
            this.departmentMap.put( department.getCompanyId() + department.getName(), department );
        }

    }

    /**
     * Get the id of the selected department.
     * @param currentCompanyId Current selected company id.
     * @return Selected department id.
     */
    public String getSelectedDepartmentId( String currentCompanyId ) {
        String selectedName = this.getSelectedItem();
        // allow null
        if ( StringUtil.isEmptyOrNull( selectedName )  ) {
            return "";
        }
        DepartmentDTO department = this.departmentMap.get( currentCompanyId + selectedName );
        return department.getId();
    }

    /**
     * Build up the new combo box allowed value, based on the provided company id.
     * @param companyId Company id to restrict list on.
     */
    public void refreshListBaseOnCompanyId( String companyId ) {
        this.removeAll();

        // build up new combo box values
        if ( this.allowNull ) {
            this.add( "" );
        }
        for ( DepartmentDTO department : this.departmentMap.values() ) {
            // add only if parent company is specified company id
            if ( department.getCompanyId().equals( companyId ) ) {
                this.add( department.getName() );
            }
        }
    }
    
    
    
}
